{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "source": [
        "import re\n",
        "import requests\n",
        "import json\n",
        "import os\n",
        "from typing import Dict, List, Tuple, Optional\n",
        "\n",
        "import os\n",
        "os.environ['GEMINI_API_KEY'] = 'Use Your Own API Key'"
      ],
      "metadata": {
        "id": "XgHqweFLd5QK"
      },
      "execution_count": 6,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class GeminiValidator:\n",
        "    \"\"\"\n",
        "    Uses Google's free Gemini API to validate and improve R code conversions\n",
        "    \"\"\"\n",
        "\n",
        "    def __init__(self, api_key: str = None):\n",
        "        \"\"\"\n",
        "        Initialize with Gemini API key\n",
        "        Get your free API key from: https://aistudio.google.com/\n",
        "        \"\"\"\n",
        "        self.api_key = api_key or os.getenv('GEMINI_API_KEY')\n",
        "        if not self.api_key:\n",
        "            print(\"⚠️  No Gemini API key provided. Set GEMINI_API_KEY environment variable\")\n",
        "            print(\"   or get a free key from: https://aistudio.google.com/\")\n",
        "\n",
        "        self.base_url = \"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent\"\n",
        "\n",
        "    def validate_conversion(self, python_code: str, r_code: str) -> Dict:\n",
        "        \"\"\"\n",
        "        Use Gemini to validate the Python to R conversion\n",
        "        \"\"\"\n",
        "        if not self.api_key:\n",
        "            return {\n",
        "                \"validation_score\": \"N/A\",\n",
        "                \"suggestions\": [\"Set up Gemini API key for validation\"],\n",
        "                \"improved_code\": r_code,\n",
        "                \"error\": \"No API key provided\"\n",
        "            }\n",
        "\n",
        "        prompt = f\"\"\"\n",
        "        You are an expert in both Python and R programming languages, especially for statistical analysis.\n",
        "\n",
        "        I have converted Python code to R code. Please validate this conversion and provide feedback.\n",
        "\n",
        "        ORIGINAL PYTHON CODE:\n",
        "        ```python\n",
        "        {python_code}\n",
        "        ```\n",
        "\n",
        "        CONVERTED R CODE:\n",
        "        ```r\n",
        "        {r_code}\n",
        "        ```\n",
        "\n",
        "        Please analyze the conversion and provide:\n",
        "        1. A validation score (0-100) for accuracy\n",
        "        2. List of any errors or issues found\n",
        "        3. Suggestions for improvement\n",
        "        4. An improved version of the R code if needed\n",
        "\n",
        "        Focus on:\n",
        "        - Correct function mappings (pandas to dplyr, numpy to base R, etc.)\n",
        "        - Proper R syntax and idioms\n",
        "        - Statistical accuracy\n",
        "        - Code efficiency and best practices\n",
        "\n",
        "        Respond in JSON format:\n",
        "        {{\n",
        "            \"validation_score\": <number>,\n",
        "            \"issues_found\": [<list of issues>],\n",
        "            \"suggestions\": [<list of suggestions>],\n",
        "            \"improved_code\": \"<improved R code>\",\n",
        "            \"summary\": \"<brief summary of the conversion quality>\"\n",
        "        }}\n",
        "        \"\"\"\n",
        "\n",
        "        try:\n",
        "            headers = {\n",
        "                'Content-Type': 'application/json',\n",
        "            }\n",
        "\n",
        "            data = {\n",
        "                \"contents\": [{\n",
        "                    \"parts\": [{\n",
        "                        \"text\": prompt\n",
        "                    }]\n",
        "                }]\n",
        "            }\n",
        "\n",
        "            response = requests.post(\n",
        "                f\"{self.base_url}?key={self.api_key}\",\n",
        "                headers=headers,\n",
        "                json=data,\n",
        "                timeout=30\n",
        "            )\n",
        "\n",
        "            if response.status_code == 200:\n",
        "                result = response.json()\n",
        "                text_response = result['candidates'][0]['content']['parts'][0]['text']\n",
        "\n",
        "                try:\n",
        "                    text_response = re.sub(r'```json\\n?', '', text_response)\n",
        "                    text_response = re.sub(r'\\n?```', '', text_response)\n",
        "\n",
        "                    validation_result = json.loads(text_response)\n",
        "                    return validation_result\n",
        "                except json.JSONDecodeError:\n",
        "                    return {\n",
        "                        \"validation_score\": \"N/A\",\n",
        "                        \"issues_found\": [\"Could not parse Gemini response\"],\n",
        "                        \"suggestions\": [text_response],\n",
        "                        \"improved_code\": r_code,\n",
        "                        \"summary\": \"Gemini response received but could not be parsed as JSON\"\n",
        "                    }\n",
        "            else:\n",
        "                return {\n",
        "                    \"validation_score\": \"N/A\",\n",
        "                    \"issues_found\": [f\"API Error: {response.status_code}\"],\n",
        "                    \"suggestions\": [\"Check API key and internet connection\"],\n",
        "                    \"improved_code\": r_code,\n",
        "                    \"summary\": f\"API request failed with status {response.status_code}\"\n",
        "                }\n",
        "\n",
        "        except Exception as e:\n",
        "            return {\n",
        "                \"validation_score\": \"N/A\",\n",
        "                \"issues_found\": [f\"Exception: {str(e)}\"],\n",
        "                \"suggestions\": [\"Check API key and internet connection\"],\n",
        "                \"improved_code\": r_code,\n",
        "                \"summary\": f\"Error during validation: {str(e)}\"\n",
        "            }"
      ],
      "metadata": {
        "id": "oHSXKYl7fWcO"
      },
      "execution_count": 7,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "class EnhancedPythonToRConverter:\n",
        "    \"\"\"\n",
        "    Enhanced Python to R converter with Gemini AI validation\n",
        "    \"\"\"\n",
        "\n",
        "    def __init__(self, gemini_api_key: str = None):\n",
        "        self.validator = GeminiValidator(gemini_api_key)\n",
        "\n",
        "        self.import_mappings = {\n",
        "            'pandas': 'library(dplyr)\\nlibrary(tidyr)\\nlibrary(readr)',\n",
        "            'numpy': 'library(base)',\n",
        "            'matplotlib.pyplot': 'library(ggplot2)',\n",
        "            'seaborn': 'library(ggplot2)\\nlibrary(RColorBrewer)',\n",
        "            'scipy.stats': 'library(stats)',\n",
        "            'sklearn': 'library(caret)\\nlibrary(randomForest)\\nlibrary(e1071)',\n",
        "            'statsmodels': 'library(stats)\\nlibrary(lmtest)',\n",
        "            'plotly': 'library(plotly)',\n",
        "        }\n",
        "\n",
        "        self.function_mappings = {\n",
        "            'pd.DataFrame': 'data.frame',\n",
        "            'pd.read_csv': 'read.csv',\n",
        "            'pd.read_excel': 'read_excel',\n",
        "            'df.head': 'head',\n",
        "            'df.tail': 'tail',\n",
        "            'df.shape': 'dim',\n",
        "            'df.info': 'str',\n",
        "            'df.describe': 'summary',\n",
        "            'df.mean': 'mean',\n",
        "            'df.median': 'median',\n",
        "            'df.std': 'sd',\n",
        "            'df.var': 'var',\n",
        "            'df.sum': 'sum',\n",
        "            'df.count': 'length',\n",
        "            'df.groupby': 'group_by',\n",
        "            'df.merge': 'merge',\n",
        "            'df.drop': 'select',\n",
        "            'df.dropna': 'na.omit',\n",
        "            'df.fillna': 'replace_na',\n",
        "            'df.sort_values': 'arrange',\n",
        "            'df.value_counts': 'table',\n",
        "\n",
        "            'np.array': 'c',\n",
        "            'np.mean': 'mean',\n",
        "            'np.median': 'median',\n",
        "            'np.std': 'sd',\n",
        "            'np.var': 'var',\n",
        "            'np.sum': 'sum',\n",
        "            'np.min': 'min',\n",
        "            'np.max': 'max',\n",
        "            'np.sqrt': 'sqrt',\n",
        "            'np.log': 'log',\n",
        "            'np.exp': 'exp',\n",
        "            'np.random.normal': 'rnorm',\n",
        "            'np.random.uniform': 'runif',\n",
        "            'np.linspace': 'seq',\n",
        "            'np.arange': 'seq',\n",
        "\n",
        "            'plt.figure': 'ggplot',\n",
        "            'plt.plot': 'geom_line',\n",
        "            'plt.scatter': 'geom_point',\n",
        "            'plt.hist': 'geom_histogram',\n",
        "            'plt.bar': 'geom_bar',\n",
        "            'plt.boxplot': 'geom_boxplot',\n",
        "            'plt.show': 'print',\n",
        "            'sns.scatterplot': 'geom_point',\n",
        "            'sns.histplot': 'geom_histogram',\n",
        "            'sns.boxplot': 'geom_boxplot',\n",
        "            'sns.heatmap': 'geom_tile',\n",
        "\n",
        "            'scipy.stats.ttest_ind': 't.test',\n",
        "            'scipy.stats.chi2_contingency': 'chisq.test',\n",
        "            'scipy.stats.pearsonr': 'cor.test',\n",
        "            'scipy.stats.spearmanr': 'cor.test',\n",
        "            'scipy.stats.normaltest': 'shapiro.test',\n",
        "            'stats.ttest_ind': 't.test',\n",
        "\n",
        "            'sklearn.linear_model.LinearRegression': 'lm',\n",
        "            'sklearn.ensemble.RandomForestRegressor': 'randomForest',\n",
        "            'sklearn.model_selection.train_test_split': 'sample',\n",
        "        }\n",
        "\n",
        "        self.syntax_patterns = [\n",
        "            (r'\\bTrue\\b', 'TRUE'),\n",
        "            (r'\\bFalse\\b', 'FALSE'),\n",
        "            (r'\\bNone\\b', 'NULL'),\n",
        "            (r'\\blen\\(', 'length('),\n",
        "            (r'range\\((\\d+)\\)', r'1:\\1'),\n",
        "            (r'range\\((\\d+),\\s*(\\d+)\\)', r'\\1:\\2'),\n",
        "            (r'\\.split\\(', '.strsplit('),\n",
        "            (r'\\.strip\\(\\)', '.str_trim()'),\n",
        "            (r'\\.lower\\(\\)', '.str_to_lower()'),\n",
        "            (r'\\.upper\\(\\)', '.str_to_upper()'),\n",
        "            (r'\\[0\\]', '[1]'),\n",
        "            (r'f\"([^\"]*)\"', r'paste0(\"\\1\")'),\n",
        "            (r\"f'([^']*)'\", r\"paste0('\\1')\"),\n",
        "        ]\n",
        "\n",
        "    def convert_imports(self, code: str) -> str:\n",
        "        \"\"\"Convert Python import statements to R library statements.\"\"\"\n",
        "        lines = code.split('\\n')\n",
        "        converted_lines = []\n",
        "\n",
        "        for line in lines:\n",
        "            line = line.strip()\n",
        "            if line.startswith('import ') or line.startswith('from '):\n",
        "                if ' as ' in line:\n",
        "                    if 'import' in line and 'as' in line:\n",
        "                        parts = line.split(' as ')\n",
        "                        module = parts[0].replace('import ', '').strip()\n",
        "                        if module in self.import_mappings:\n",
        "                            converted_lines.append(f\"# {line}\")\n",
        "                            converted_lines.append(self.import_mappings[module])\n",
        "                        else:\n",
        "                            converted_lines.append(f\"# {line} # No direct R equivalent\")\n",
        "                    elif 'from' in line and 'import' in line and 'as' in line:\n",
        "                        converted_lines.append(f\"# {line} # Handle specific imports manually\")\n",
        "                elif line.startswith('from '):\n",
        "                    parts = line.split(' import ')\n",
        "                    module = parts[0].replace('from ', '').strip()\n",
        "                    if module in self.import_mappings:\n",
        "                        converted_lines.append(f\"# {line}\")\n",
        "                        converted_lines.append(self.import_mappings[module])\n",
        "                    else:\n",
        "                        converted_lines.append(f\"# {line} # No direct R equivalent\")\n",
        "                else:\n",
        "                    module = line.replace('import ', '').strip()\n",
        "                    if module in self.import_mappings:\n",
        "                        converted_lines.append(f\"# {line}\")\n",
        "                        converted_lines.append(self.import_mappings[module])\n",
        "                    else:\n",
        "                        converted_lines.append(f\"# {line} # No direct R equivalent\")\n",
        "            else:\n",
        "                converted_lines.append(line)\n",
        "\n",
        "        return '\\n'.join(converted_lines)\n",
        "\n",
        "    def convert_functions(self, code: str) -> str:\n",
        "        \"\"\"Convert Python function calls to R equivalents.\"\"\"\n",
        "        for py_func, r_func in self.function_mappings.items():\n",
        "            code = code.replace(py_func, r_func)\n",
        "        return code\n",
        "\n",
        "    def apply_syntax_patterns(self, code: str) -> str:\n",
        "        \"\"\"Apply regex patterns to convert Python syntax to R syntax.\"\"\"\n",
        "        for pattern, replacement in self.syntax_patterns:\n",
        "            code = re.sub(pattern, replacement, code)\n",
        "        return code\n",
        "\n",
        "    def convert_pandas_operations(self, code: str) -> str:\n",
        "        \"\"\"Convert common pandas operations to dplyr/tidyr equivalents.\"\"\"\n",
        "        code = re.sub(r'df\\[[\\'\"](.*?)[\\'\"]\\]', r'df$\\1', code)\n",
        "        code = re.sub(r'df\\.(\\w+)', r'df$\\1', code)\n",
        "\n",
        "        code = re.sub(r'df\\[df\\[[\\'\"](.*?)[\\'\"]\\]\\s*([><=!]+)\\s*([^]]+)\\]', r'df[df$\\1 \\2 \\3, ]', code)\n",
        "\n",
        "        return code\n",
        "\n",
        "    def convert_plotting(self, code: str) -> str:\n",
        "        \"\"\"Convert matplotlib/seaborn plotting to ggplot2.\"\"\"\n",
        "        conversions = [\n",
        "            (r'plt\\.figure\\(figsize=\\((\\d+),\\s*(\\d+)\\)\\)', r'# Set figure size in ggplot theme'),\n",
        "            (r'plt\\.title\\([\\'\"](.*?)[\\'\\\"]\\)', r'+ ggtitle(\"\\1\")'),\n",
        "            (r'plt\\.xlabel\\([\\'\"](.*?)[\\'\\\"]\\)', r'+ xlab(\"\\1\")'),\n",
        "            (r'plt\\.ylabel\\([\\'\"](.*?)[\\'\\\"]\\)', r'+ ylab(\"\\1\")'),\n",
        "            (r'plt\\.legend\\(\\)', r'+ theme(legend.position=\"right\")'),\n",
        "            (r'plt\\.grid\\(True\\)', r'+ theme(panel.grid.major = element_line())'),\n",
        "        ]\n",
        "\n",
        "        for pattern, replacement in conversions:\n",
        "            code = re.sub(pattern, replacement, code)\n",
        "\n",
        "        return code\n",
        "\n",
        "    def add_r_context(self, code: str) -> str:\n",
        "        \"\"\"Add R-specific context and comments.\"\"\"\n",
        "        r_header = '''# R Statistical Analysis Code\n",
        "# Converted from Python using Enhanced Converter with Gemini AI Validation\n",
        "# Install required packages: install.packages(c(\"dplyr\", \"ggplot2\", \"tidyr\", \"readr\"))\n",
        "\n",
        "'''\n",
        "        return r_header + code\n",
        "\n",
        "    def convert_code(self, python_code: str) -> str:\n",
        "        \"\"\"Main conversion method that applies all transformations.\"\"\"\n",
        "        code = python_code.strip()\n",
        "\n",
        "        code = self.convert_imports(code)\n",
        "        code = self.convert_functions(code)\n",
        "        code = self.convert_pandas_operations(code)\n",
        "        code = self.convert_plotting(code)\n",
        "        code = self.apply_syntax_patterns(code)\n",
        "        code = self.add_r_context(code)\n",
        "\n",
        "        return code\n",
        "\n",
        "    def convert_and_validate(self, python_code: str, use_gemini: bool = True) -> Dict:\n",
        "        \"\"\"\n",
        "        Convert Python code to R and validate with Gemini AI\n",
        "        \"\"\"\n",
        "        r_code = self.convert_code(python_code)\n",
        "\n",
        "        result = {\n",
        "            \"original_python\": python_code,\n",
        "            \"converted_r\": r_code,\n",
        "            \"validation\": None\n",
        "        }\n",
        "\n",
        "        if use_gemini and self.validator.api_key:\n",
        "            print(\"🔍 Validating conversion with Gemini AI...\")\n",
        "            validation = self.validator.validate_conversion(python_code, r_code)\n",
        "            result[\"validation\"] = validation\n",
        "\n",
        "            if validation.get(\"improved_code\") and validation.get(\"improved_code\") != r_code:\n",
        "                result[\"final_r_code\"] = validation[\"improved_code\"]\n",
        "            else:\n",
        "                result[\"final_r_code\"] = r_code\n",
        "        else:\n",
        "            result[\"final_r_code\"] = r_code\n",
        "            if not self.validator.api_key:\n",
        "                result[\"validation\"] = {\"note\": \"Set GEMINI_API_KEY for AI validation\"}\n",
        "\n",
        "        return result\n",
        "\n",
        "    def print_results(self, results: Dict):\n",
        "        \"\"\"Pretty print the conversion results\"\"\"\n",
        "        print(\"=\" * 80)\n",
        "        print(\"🐍 ORIGINAL PYTHON CODE\")\n",
        "        print(\"=\" * 80)\n",
        "        print(results[\"original_python\"])\n",
        "\n",
        "        print(\"\\n\" + \"=\" * 80)\n",
        "        print(\"📊 CONVERTED R CODE\")\n",
        "        print(\"=\" * 80)\n",
        "        print(results[\"final_r_code\"])\n",
        "\n",
        "        if results.get(\"validation\"):\n",
        "            validation = results[\"validation\"]\n",
        "            print(\"\\n\" + \"=\" * 80)\n",
        "            print(\"🤖 GEMINI AI VALIDATION\")\n",
        "            print(\"=\" * 80)\n",
        "\n",
        "            if validation.get(\"validation_score\"):\n",
        "                print(f\"📈 Score: {validation['validation_score']}/100\")\n",
        "\n",
        "            if validation.get(\"summary\"):\n",
        "                print(f\"📝 Summary: {validation['summary']}\")\n",
        "\n",
        "            if validation.get(\"issues_found\"):\n",
        "                print(\"\\n⚠️  Issues Found:\")\n",
        "                for issue in validation[\"issues_found\"]:\n",
        "                    print(f\"   • {issue}\")\n",
        "\n",
        "            if validation.get(\"suggestions\"):\n",
        "                print(\"\\n💡 Suggestions:\")\n",
        "                for suggestion in validation[\"suggestions\"]:\n",
        "                    print(f\"   • {suggestion}\")"
      ],
      "metadata": {
        "id": "BY3FtqwGfeX5"
      },
      "execution_count": 9,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def setup_gemini_key():\n",
        "    \"\"\"\n",
        "    Instructions for setting up Gemini API key\n",
        "    \"\"\"\n",
        "    print(\"🔑 SETTING UP GEMINI API KEY\")\n",
        "    print(\"=\" * 50)\n",
        "    print(\"1. Go to https://aistudio.google.com/\")\n",
        "    print(\"2. Sign in with your Google account\")\n",
        "    print(\"3. Click 'Get API Key'\")\n",
        "    print(\"4. Create a new API key\")\n",
        "    print(\"5. Copy the key and set it as environment variable:\")\n",
        "    print(\"   For Colab: import os; os.environ['GEMINI_API_KEY'] = 'your_key_here'\")\n",
        "    print(\"   For local: export GEMINI_API_KEY='your_key_here'\")\n",
        "    print(\"\\n✅ The API is FREE to use within generous limits!\")\n",
        "\n",
        "def demo_with_gemini():\n",
        "    \"\"\"\n",
        "    Demo function that shows how to use the enhanced converter\n",
        "    \"\"\"\n",
        "    print(\"🚀 ENHANCED PYTHON TO R CONVERTER WITH GEMINI AI\")\n",
        "    print(\"=\" * 60)\n",
        "\n",
        "    api_key = os.getenv('GEMINI_API_KEY')\n",
        "    if not api_key:\n",
        "        print(\"⚠️  No Gemini API key found. Running without validation.\")\n",
        "        setup_gemini_key()\n",
        "        print(\"\\n\" + \"=\" * 60)\n",
        "\n",
        "    converter = EnhancedPythonToRConverter(api_key)\n",
        "\n",
        "    python_example = '''\n",
        "import pandas as pd\n",
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "from scipy import stats\n",
        "\n",
        "# Load and analyze data\n",
        "df = pd.read_csv('sales_data.csv')\n",
        "print(df.head())\n",
        "print(df.describe())\n",
        "\n",
        "# Statistical analysis\n",
        "mean_sales = df['sales'].mean()\n",
        "std_sales = df['sales'].std()\n",
        "correlation = df['sales'].corr(df['marketing_spend'])\n",
        "\n",
        "# Data filtering and grouping\n",
        "high_sales = df[df['sales'] > mean_sales]\n",
        "monthly_avg = df.groupby('month')['sales'].mean()\n",
        "\n",
        "# Visualization\n",
        "plt.figure(figsize=(10, 6))\n",
        "plt.scatter(df['marketing_spend'], df['sales'])\n",
        "plt.title('Sales vs Marketing Spend')\n",
        "plt.xlabel('Marketing Spend')\n",
        "plt.ylabel('Sales')\n",
        "plt.show()\n",
        "\n",
        "# Statistical test\n",
        "t_stat, p_value = stats.ttest_ind(df['sales'], df['competitor_sales'])\n",
        "print(f\"T-test result: {t_stat:.3f}, p-value: {p_value:.3f}\")\n",
        "'''\n",
        "\n",
        "    results = converter.convert_and_validate(python_example, use_gemini=bool(api_key))\n",
        "\n",
        "    converter.print_results(results)\n",
        "\n",
        "    return results"
      ],
      "metadata": {
        "id": "scS4OuvefhH5"
      },
      "execution_count": 8,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def colab_setup():\n",
        "    \"\"\"\n",
        "    Easy setup function for Google Colab\n",
        "    \"\"\"\n",
        "    print(\"📱 GOOGLE COLAB SETUP\")\n",
        "    print(\"=\" * 40)\n",
        "    print(\"1. Run this cell to install dependencies:\")\n",
        "    print(\"   !pip install requests\")\n",
        "    print(\"\\n2. Set your Gemini API key:\")\n",
        "    print(\"   import os\")\n",
        "    print(\"   os.environ['GEMINI_API_KEY'] = 'your_key_here'\")\n",
        "    print(\"\\n3. Run the demo:\")\n",
        "    print(\"   results = demo_with_gemini()\")\n",
        "\n",
        "if __name__ == \"__main__\":\n",
        "    demo_with_gemini()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "8yVXZ9xZcDv7",
        "outputId": "db55895c-732d-460d-c66b-d31ec315c5ef"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "🚀 ENHANCED PYTHON TO R CONVERTER WITH GEMINI AI\n",
            "============================================================\n",
            "🔍 Validating conversion with Gemini AI...\n",
            "================================================================================\n",
            "🐍 ORIGINAL PYTHON CODE\n",
            "================================================================================\n",
            "\n",
            "import pandas as pd\n",
            "import numpy as np\n",
            "import matplotlib.pyplot as plt\n",
            "from scipy import stats\n",
            "\n",
            "# Load and analyze data\n",
            "df = pd.read_csv('sales_data.csv')\n",
            "print(df.head())\n",
            "print(df.describe())\n",
            "\n",
            "# Statistical analysis\n",
            "mean_sales = df['sales'].mean()\n",
            "std_sales = df['sales'].std()\n",
            "correlation = df['sales'].corr(df['marketing_spend'])\n",
            "\n",
            "# Data filtering and grouping\n",
            "high_sales = df[df['sales'] > mean_sales]\n",
            "monthly_avg = df.groupby('month')['sales'].mean()\n",
            "\n",
            "# Visualization\n",
            "plt.figure(figsize=(10, 6))\n",
            "plt.scatter(df['marketing_spend'], df['sales'])\n",
            "plt.title('Sales vs Marketing Spend')\n",
            "plt.xlabel('Marketing Spend')\n",
            "plt.ylabel('Sales')\n",
            "plt.show()\n",
            "\n",
            "# Statistical test\n",
            "t_stat, p_value = stats.ttest_ind(df['sales'], df['competitor_sales'])\n",
            "print(f\"T-test result: {t_stat:.3f}, p-value: {p_value:.3f}\")\n",
            "\n",
            "\n",
            "================================================================================\n",
            "📊 CONVERTED R CODE\n",
            "================================================================================\n",
            "r\n",
            "# Install required packages if not already installed\n",
            "if(!require(dplyr)){install.packages('dplyr')};if(!require(ggplot2)){install.packages('ggplot2')};if(!require(readr)){install.packages('readr')}\n",
            "\n",
            "# Load libraries\n",
            "library(dplyr)\n",
            "library(ggplot2)\n",
            "library(readr)\n",
            "library(stats)\n",
            "\n",
            "# Check if file exists\n",
            "if (!file.exists('sales_data.csv')) {\n",
            "  stop(\"Error: sales_data.csv not found.\")\n",
            "}\n",
            "\n",
            "# Load data and check for necessary columns\n",
            "df <- read_csv('sales_data.csv')\n",
            "if (!all(c('sales', 'marketing_spend', 'competitor_sales', 'month') %in% names(df))) {\n",
            "  stop(\"Error: sales_data.csv must contain 'sales', 'marketing_spend', 'competitor_sales', and 'month' columns.\")\n",
            "}\n",
            "\n",
            "# Data analysis\n",
            "print(head(df))\n",
            "print(summary(df))\n",
            "\n",
            "mean_sales <- mean(df$sales)\n",
            "std_sales <- sd(df$sales)\n",
            "correlation <- cor(df$sales, df$marketing_spend)\n",
            "\n",
            "high_sales <- filter(df, sales > mean_sales)\n",
            "monthly_avg <- df %>% group_by(month) %>% summarise(avg_sales = mean(sales))\n",
            "\n",
            "# Visualization\n",
            "ggplot(df, aes(x = marketing_spend, y = sales)) +\n",
            "  geom_point() +\n",
            "  ggtitle(\"Sales vs Marketing Spend\") +\n",
            "  xlab(\"Marketing Spend\") +\n",
            "  ylab(\"Sales\")\n",
            "\n",
            "# Statistical test\n",
            "t_test_result <- t.test(df$sales, df$competitor_sales)\n",
            "t_stat <- t_test_result$statistic\n",
            "p_value <- t_test_result$p.value\n",
            "print(paste0(\"T-test result: \", round(t_stat, 3), \", p-value: \", round(p_value, 3)))\n",
            "\n",
            "\n",
            "================================================================================\n",
            "🤖 GEMINI AI VALIDATION\n",
            "================================================================================\n",
            "📈 Score: 75/100\n",
            "📝 Summary: The original R conversion had several significant issues related to function usage and syntax within ggplot2 and dplyr. The improved code addresses these, incorporates error handling and  demonstrates a better understanding of R's data manipulation and visualization capabilities. The validation score reflects this improvement.\n",
            "\n",
            "⚠️  Issues Found:\n",
            "   • Incorrect use of `print(head())` and `print(summary())`.  These need to reference the dataframe `df`. \n",
            "   • Incorrect syntax in plotting with `ggplot2`.  `ggplot2` uses a grammar of graphics approach.\n",
            "   • The `monthly_avg` calculation is incorrect.  The `group_by()` function needs to be used correctly with the `summarize()` or `summarise()` function in `dplyr`.\n",
            "   • Incorrect string formatting in the final print statement. R's `paste0()` doesn't support Python's f-string style formatting.\n",
            "   • Missing error handling: the code assumes `sales_data.csv` exists and has the necessary columns.  Robust code would check for file existence and column presence.\n",
            "   • The `base::corr()` function is not used correctly and will return an error. The correct way is to use the `cor()` function.\n",
            "   • Missing library call for `t.test` function. The library `stats` is required but is not included\n",
            "\n",
            "💡 Suggestions:\n",
            "   • Use the `head(df)` and `summary(df)` functions correctly to display the data.\n",
            "   • Learn and properly utilize the grammar of graphics in `ggplot2` for data visualization.\n",
            "   • Use the `dplyr` package's `group_by()` and `summarize()` functions appropriately for aggregation.\n",
            "   • Use `paste()` or `sprintf()` for string formatting in R.\n",
            "   • Add error handling to check file existence and column availability. \n",
            "   • Use the `cor()` function for correlation calculation.\n",
            "   • Explicitly load the `stats` package to avoid errors related to `t.test`\n"
          ]
        }
      ]
    }
  ]
}